<template>
  <div class="basicInfo flowCloumn w100 h100">
    <!-- <div
      class="constentTop flowWrap"
      v-loading.fullscreen.lock="fullscreenLoading"
    >
      <span class="topBtn">
        <el-button
          class="el-button--plain"
          size="mini"
          icon="el-icon-edit"
          @click="doEdit"
          v-if="showEdit&&menuType!='paramInfor'"
          >编辑</el-button
        >
        <div class="editBtn" v-if="showBtn">
          <el-tooltip
            class="item"
            effect="dark"
            :content="addContent"
            :disabled="addDisabled"
            placement="top"
          >
            <span class="btnSpan">
              <el-popover
                placement="bottom"
                width="60"
                trigger="click"
                class="popoverBtn"
                v-if="showAddBtn"
                :disabled="!addDisabled"
              >
                <div class="addBtn" @click="toAdd('root')">在根节点新建</div>
                <div class="addBtn" @click="toAdd('current')">
                  在当前节点新建
                </div>
                <div class="addBtn">
                  <el-upload
                    ref="upload"
                    action="#"
                    :accept="acceptFile"
                    :file-list="uploadFiles"
                    :show-file-list="false"
                    :http-request="saveFiles"
                  >
                    <el-button class="importBtn" size="small"
                      >台账导入</el-button
                    >
                  </el-upload>
                </div>
                <el-button
                  slot="reference"
                  icon="el-icon-plus"
                  class="el-button--plain"
                  size="mini"
                  ref="addBtn"
                  :disabled="!addDisabled"
                  >新建</el-button
                >
              </el-popover>
            </span>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            :content="saveContent"
            :disabled="saveDisabled"
            placement="top"
          >
            <span class="btnSpan">
              <el-button
                class="el-button--plain"
                size="mini"
                icon="el-icon-check"
                @click="submit"
                v-if="showSaveBtn"
                :disabled="!saveDisabled"
                >保存</el-button
              >
            </span>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            :content="deleteContent"
            :disabled="deleteDisabled"
            placement="top"
          >
            <span class="btnSpan">
              <el-button
                class="el-button--plain"
                size="mini"
                icon="el-icon-delete"
                @click="deleteRow"
                v-if="showDeleteBtn"
                :disabled="!deleteDisabled"
                >删除</el-button
              >
            </span>
          </el-tooltip>

          <el-tooltip
            class="item"
            effect="dark"
            :content="moveContent"
            :disabled="moveDisabled"
            placement="top"
          >
            <span class="btnSpan">
              <el-button
                class="el-button--plain"
                size="mini"
                icon="el-icon-rank"
                @click="moveMethods"
                v-if="showDeleteBtn"
                :disabled="!moveDisabled"
                >移动节点</el-button
              >
            </span>
          </el-tooltip>
          <el-button
            class="el-button--plain"
            size="mini"
            icon="el-icon-check"
            @click="cancel"
            v-if="showCanceln"
            >取消</el-button
          >
        </div>
        <el-popover
          placement="bottom"
          title="下载进度"
          width="300"
          trigger="manual"
          v-model="visible"
        >
          <el-progress
            :percentage="percentage"
            :color="customColorMethod"
          ></el-progress>

          <el-button
            style="margin: 0 10px"
            class="el-button--plain"
            size="mini"
            icon="el-icon-download"
            slot="reference"
            v-if="showQrCodeLoad"
            @click="downloadQRcode()"
            >批量下载二维码</el-button
          >
        </el-popover>
        <el-popover
          placement="bottom"
          width="100"
          trigger="click"
          ref="firstPopover"
        >
          <div class="moreBtnContent">
            <template v-for="(moreItem, moreIndex) in moreBtnArr">
              <el-tooltip
                class="item"
                effect="dark"
                :content="moreItem.content"
                :disabled="!moreItem.disabled"
                :placement="moreItem.placement || 'left'"
                :key="moreIndex"
              >
                <span class="tipContent">
                  <span
                    v-if="!moreItem.hide && moreItem.child && moreItem.disabled"
                    :class="{
                      moreItem: true,
                      ableMoreItem: !moreItem.disabled,
                      disMoreItem: moreItem.disabled,
                    }"
                    :key="moreIndex"
                    @click="!moreItem.disabled ? moreItem.methods : ''"
                  >
                    <i :class="moreItem.icon"></i>
                    <span class="moreItemText">{{ moreItem.text }}</span>
                  </span>
                  <el-popover
                    v-else-if="
                      !moreItem.hide && moreItem.child && !moreItem.disabled
                    "
                    :key="moreIndex"
                    width="200"
                    trigger="hover"
                    placement="left"
                  >
                    <div class="moreBtnContent">
                      <template
                        v-for="(childItem, childIndex) in moreItem.child"
                      >
                        <span
                          class="moreItem"
                          :key="childIndex"
                          @click="moreItem.methods(childItem)"
                        >
                          <span class="childItemText">
                            {{ childItem.name }}
                          </span>
                        </span>
                      </template>
                    </div>
                    <el-button slot="reference" type="plain">
                      {{ moreItem.text }}
                    </el-button>
                  </el-popover>
                  <span
                    v-else-if="!moreItem.hide"
                    :class="{
                      moreItem: true,
                      ableMoreItem: !moreItem.disabled,
                      disMoreItem: moreItem.disabled,
                    }"
                    :key="moreIndex"
                    @click="moreItem.methods(moreItem.disabled)"
                  >
                    <i :class="moreItem.icon"></i>
                    <span class="moreItemText">{{ moreItem.text }}</span>
                  </span>
                </span>
              </el-tooltip>
            </template>
          </div>
          <el-button
            slot="reference"
            size="mini"
            type="plain"
            icon="icon-xiazai"
            class="btn-text-blue"
            ref="moreBtn"
            v-if="this.menuType == 'paramInfor'"
            >导出下载</el-button
          >
        </el-popover>
      </span>
      <el-tooltip
        class="item"
        effect="dark"
        content="角色未授权"
        :disabled="importParam"
        :placement="'top'"
      >
        <el-dropdown
          size="small"
          trigger="click"
          @command="download"
          v-if="this.menuType != 'paramInfor'"
          style="margin: 0 10px"
        >
          <el-button
            size="mini"
            class="icon-daoru"
            type="plain"
            :disabled="!importParam"
          >
            导入基本参数
            <i class="el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              v-for="(item, index) in basicParams"
              :key="index"
              :command="item"
              >{{ item.name }}</el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>
      </el-tooltip>
      <el-tooltip
        class="item"
        effect="dark"
        content="角色未授权"
        :disabled="importTechParam"
        :placement="'top'"
      >
        <span>
          <el-button
            class="el-button--plain icon-daoru"
            size="mini"
            @click="doImportTechParam"
            v-if="this.menuType != 'paramInfor'"
            :disabled="!importTechParam"
            >导入技术参数</el-button
          >
        </span>
      </el-tooltip>
    </div> -->
    <div class="constentBttom flowWrap">
      <div class="constentmain w100" v-if="showMain">
        <el-collapse v-model="activeNames" class="collapseDiv">
          <!-- <el-collapse-item name="1">
            <template slot="title">身份信息</template>
            <div class="w100">
              <div class="baseDiv">
                <div class="formDiv">
                  <editForm
                    :formConfig="basicConfig"
                    ref="basicForm"
                    :formData="formData"
                  ></editForm>
                </div>
                <div class="imgDiv" v-if="!isVirtual">
                  <div class="imgLeft">
                    <el-image
                      class="elImg"
                      style="width: 100px; height: 100px"
                      :src="imgUrl"
                      :preview-src-list="imgList"
                      fit="scale-down"
                    >
                      <div slot="error" class="image-slot errText">
                        <i class="el-icon-picture-outline"></i>
                      </div>
                    </el-image>
                    <span class="el-upload-actions" v-if="deviceImg.id">
                      <span
                        class="el-upload-icon"
                        @click="handlePictureCardPreview()"
                      >
                        <i class="el-icon-zoom-in"></i>
                      </span>
                      <span
                        v-if="saveDisabled"
                        class="el-upload-icon"
                        @click="handleRemove()"
                      >
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </div>
                  <div class="imgRight">
                    <div class="imgText">
                      <el-upload
                        ref="fileUpload"
                        class="uploadFile"
                        action="#"
                        :limit="1"
                        :file-list="fileList"
                        :accept="acceptType"
                        :show-file-list="false"
                        :before-upload="beforeUpload"
                        :http-request="saveItemFile"
                      >
                        <el-button
                          size="small"
                          class="el-button--plain"
                          v-if="showImgBtn"
                          >点击上传图片</el-button
                        >
                        <el-button
                          class="el-button--plain"
                          size="mini"
                          icon="el-icon-s-grid"
                          @click.stop="(event) => viewQrCode(event, true)"
                          v-if="!isVirtual && menuType == 'paramInfor'"
                          >查看二维码</el-button
                        >
                        <div slot="tip" class="el-upload__tip">
                          <br />格式要求： <br />1、格式必须为jpg或png
                          <br />2、大小不能超过1MB <br />（超出系统会自动压缩）
                        </div>
                      </el-upload>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-collapse-item> -->
          <el-collapse-item name="2" v-if="!isVirtual">
            <template slot="title">基本参数</template>
            <editForm
              v-if="showCustombasic"
              :formConfig="basicParamsConfig"
              :customArr="customArr"
              ref="basicParamsForm"
              :formData="basicParamsData"
              :parameterList="parameterList"
              :parameterNode="moveCurrentNodeId"
            >
            </editForm>
          </el-collapse-item>

          <el-collapse-item name="3" v-if="showEntity">
            <template slot="title">技术参数</template>
            <editForm
              v-if="showCustomEntity"
              :formConfig="entityConfig"
              :customArr="customArr"
              ref="entityForm"
              :formData="entityData"
              :parameterList="parameterList"
              :parameterNode="moveCurrentNodeId"
            ></editForm>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>
    <moveTree
      :currentNode="currentNode"
      @changeSelete="submitNode"
      ref="moveTree"
    ></moveTree>

    <div
      class="codeDiv"
      v-if="showQrCode"
      :class="{ topDistance: !showBtn }"
      :style="{ height: '340px' }"
    >
      <div class="codeTop">
        <span class="codeTitle">二维码</span>
        <span class="codeClose" @click="() => (showQrCode = false)">
          <i class="el-icon-close"></i>
        </span>
      </div>
      <div class="codeContent" ref="codeImg">
        <div
          class="codeName"
          style="
            height: 30px;
            line-height: 30px;
            font-size: 18px;
            margin-bottom: 20px;
          "
        >
          {{ currentNode.name }}
        </div>
        <div class="QRCode" style="display: none" ref="qrCodeUrl"></div>
      </div>
      <div class="codeBtn">
        <el-button
          slot="reference"
          icon="el-icon-printer"
          class="el-button--plain"
          size="mini"
          @click="printCode"
          >打印</el-button
        >
        <el-button
          class="el-button--plain"
          size="mini"
          icon="el-icon-download"
          @click="(event) => loadQrCode()"
          >下载</el-button
        >
      </div>
    </div>
    <qrCode ref="qrCode" @downLoadSuccess="downLoadSuccess"></qrCode>
    <image-viewer
      v-if="showViewer"
      :on-close="closeViewer"
      :imgIdList="imgIdList"
    />
    <div
        ref="canvasImg"
        style="
          width: 280px;
          height: 420px;
          position: absolute;
          z-index: -999;
          left: 25%;
          top: 10%;
        "
      >
        <el-image
          style="
            width: 280px;
            height: 420px;
            border-radius: 10px;
            border: 1px solid rgb(116, 116, 116);
          "
          :src="canvasUrl"
          fit="scale-down"
        >
        </el-image>
      </div>
    <dialogPublic
      :title="'导入基本参数'"
      :show.sync="show"
      width="40%"
      :noFootBtn="true"
    >
      <div style="text-align: left; height: 200px" v-if="show">
        <el-upload
          class="upload-demo"
          :action="uploadUrl"
          :on-change="handleChange"
          :multiple="false"
          :auto-upload="false"
          accept=".xls,.xlsx"
        >
          <el-button slot="trigger" size="small" type="primary"
            >选取文件</el-button
          >
          <el-button
            style="margin-left: 10px"
            size="small"
            type="success"
            @click="submitUpload"
            >上传到服务器</el-button
          >
          <div class="el-upload__tip" slot="tip">
            只能上传excle文件，且不超过500kb
          </div>
        </el-upload>
        <el-button v-if="path != ''" type="text" @click="downLoadResult"
          >下载错误备注文件</el-button
        >
      </div>
    </dialogPublic>
  </div>
</template>
<script>
import {
  getConfigApi,
  getEquipment,
  updateApi, //修改
  insertApi, //新增
  deleteApi, //删除
  moveNode,
  getFloorApi, //获取层级数据
  getCodeApi, //获取二维码
  exportDevicesApi, //导出节点设备
  exportModelApi, //导出台账模板
  exportErrorApi, //下载导入错误表格
  uploadParameterApi, //台账导入
  uploadBasicParams, //基本参数导入
  uploadTechParams, //技术参数导入
  getEquipmentByParentId,
} from "@/api/equipmentLedger/equipmentManage";
import {
  uploadFileApi, //附件上传（删除原先的业务附件, 每次上传, 需上传所有的附件）
  getAttachList,
} from "@/api/common";
import { baseParamList } from "@/api/standardManagement/acountManagement.js";
import preview from "@/components/attach/preview";
// import moveTree from "./moveTree";
import moveTree from '@/views/equipmentLedger/equipmentManage/moveTree'
import { Loading } from "element-ui";
import ImageViewer from "@/components/attach/image-viewer";
import {
  deleteFiles, //删除单个附件通过文件id
} from "@/api/common";
// import treeVue from "../../../components/memberSelect/tree.vue";
import treeVue from '@/components/memberSelect/tree.vue'
// import qrCode from "./qrCode.vue";
import qrCode from '@/views/equipmentLedger/equipmentManage/qrCode'
import QRCode from "qrcodejs2";
import { set } from "vue";
let prevOverflow = "";
export default {
  props: {
    moveCurrentNodeId: {
      type: String,
      default: ''
    },
    //当前设备
    currentNode: {
      type: Object,
      default: () => {
        return {};
      },
    },
    menuType: {
      type: String,
      default: "paramInfor",
    },
    parameterList: {
      type: Array,
      default: () => []
    },
    popupType: {
      type: String,
      default: ''
    }
  },
  components: { moveTree, ImageViewer, qrCode},
  inject: ['updateOldEquipmentMoveParams', 'getPreviousParams'],
  data() {
    return {
      show: false,
      showEdit: true,
      showCode: false,
      path: "",
      fileName: null,
      uploadUrl: `${process.env.VUE_APP_BASEURL}/eam-service-standard/patrol/import`,
      backgroundImgUrl: require("@/assets/img/logo_blue.png"),
      canvasUrl: null,
      showViewer: false,
      imgIdList: [],
      deviceImg: {},
      queryName: "",
      errorFileName: "",
      addType: "",
      codeUrl: "",
      imgUrl: "",
      qrCodeUrl: "",
      codeData: "",
      //当前预览文件
      currentAttach: {},
      imgList: [],
      fileList: [],
      uploadFiles: [],
      activeNames: ["1", "2", "3"],
      acceptType: ".jpg,.png",
      acceptFile: ".xlsx,.xls",
      updataType: false,
      fullscreenLoading: false,
      pageType: "edit",
      hideBtn: true,
      showSelete: false,
      showQrCode: false,
      showCustombasic: false,
      showCustomEntity: false,
      treeNode: {},
      formData: {},
      entityData: {},
      basicParamsData: {},
      showMain: false,
      basicConfig: {
        itemArr: [],
      },
      customArr: {},
      basicParamsConfig: {
        itemArr: [],
        customRules: true  // 是否自定义校验规则
      },
      entityConfig: {
        itemArr: [],
        customRules: true
      },
      config: { color: "green", imagePath: require("@/assets/logo.png") },
      paramsList: [],
      entityList: [],
      basicList: [],
      beforeNode: {},
      afterNode: {},
      deptOption: [],
      deptOption1: [],
      selectDevice: {},
      saveNode: {},
      basicParams: [],
      uploadParams: {},
      percentage: 0,
      visible: false,
      timerInterval: null,
      // 记录当前设备所有变更前参数
      oldEquipmentMoveParams: {},
    };
  },
  watch: {
    currentNode: {
      handler: function (newVal, oldVal) {
        if (this.pageType == "add") {
          this.cancel();
        }
        if (
          JSON.stringify(newVal) != "{}" &&
          (JSON.stringify(this.saveNode) === "{}" ||
            this.saveNode.id == newVal.id)
        ) {
          this.treeNode = Object.assign({}, newVal);
          this.getDetails();
          this.getImage();
        }
        this.showQrCode = false;
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    classObject() {
      return this.menuType == "paramInfor" ? "icon-daochu" : "icon-daoru";
    },
    isVirtual() {
      return this.treeNode.isVirtual == "1";
    },
    showEntity() {
      return this.treeNode.isVirtual == "0" && this.entityConfig.itemArr.length;
    },
    showImgBtn() {
      return (
        !["details", "paramInfor"].includes(this.pageType) && this.saveDisabled
      );
    },
    showAddBtn() {
      return this.pageType != "add" && this.treeNode.id;
    },
    showCanceln() {
      return this.pageType == "add";
    },
    showSaveBtn() {
      return this.pageType == "add" || this.treeNode.id;
    },
    showDeleteBtn() {
      //新增的时候
      return this.treeNode.id && this.pageType != "add";
    },
    showBtn() {
      return !["paramInfor"].includes(this.pageType) && !this.showEdit;
    },
    //展示批量下载二维码
    showQrCodeLoad() {
      return this.menuType == "paramInfor" && this.treeNode.level > 3;
    },
    addContent() {
      return this.$store.getters["isBtnAuth"]("add") ? null : "未授权此功能！";
    },
    addDisabled() {
      return this.$store.getters["isBtnAuth"]("add");
    },
    saveContent() {
      return this.$store.getters["isBtnAuth"]("edit") ? null : "未授权此功能！";
    },
    saveDisabled() {
      return this.$store.getters["isBtnAuth"]("edit");
    },
    deleteContent() {
      return this.$store.getters["isBtnAuth"]("delete")
        ? null
        : "未授权此功能！";
    },
    deleteDisabled() {
      return this.$store.getters["isBtnAuth"]("delete");
    },
    moveContent() {
      return this.$store.getters["isBtnAuth"]("move") ? null : "未授权此功能！";
    },
    moveDisabled() {
      return this.$store.getters["isBtnAuth"]("move");
    },
    exportParam() {
      return this.$store.getters["isBtnAuth"]("exportParam");
    },
    importParam() {
      return this.$store.getters["isBtnAuth"]("importParam");
    },
    exportTechParam() {
      return this.$store.getters["isBtnAuth"]("exportTechParam");
    },
    importTechParam() {
      return this.$store.getters["isBtnAuth"]("importTechParam");
    },
    moreBtnArr() {
      let arr = [
        {
          text: "导出节点设备",
          methods: (val) => {
            this.exportDevices("equipment");
          },
          hide: false,
          content: "",
          disabled: false,
        },
        {
          text: "导出台账模板",
          methods: (val) => {
            this.exportDevices("model");
          },
          hide: false,
          content: "",
          disabled: false,
        },
        {
          text: "导出基本参数",
          methods: (val) => {
            this.download(val);
          },
          hide: false,
          isDictionary: true, //是否是数据字典
          child: this.basicParams,
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "application",
            this.$store.getters["isBtnAuth"]("application")
          ),
          disabled: !this.$store.getters["isBtnAuth"]("exportParam"),
        },
        {
          text: "导出技术参数",
          methods: (val) => {
            if (!val) {
              this.doExportTechParam();
            }
          },
          hide: false,
          content: this.$utils.getJurisdictionContent(
            this.btnJurisdiction,
            "application",
            this.$store.getters["isBtnAuth"]("application")
          ),
          disabled: !this.$store.getters["isBtnAuth"]("exportTechParam"),
        },
      ];
      return arr;
    },
  },
  created() {},
  mounted() {
    this.init();
  },
  methods: {
    init() {
      let isEdit = this.$store.getters["isBtnAuth"]("edit");
      if (this.menuType != "paramInfor") {
        this.pageType = isEdit ? this.menuType : "details";
      } else {
        this.pageType = this.menuType;
      }

      if (["paramInfor", "details"].includes(this.pageType)) {
        this.entityData = {};
        this.basicParamsData = {};
        this.showCustombasic = false;
        this.showCustomEntity = false;
        this.saveNode = {};
      }
      baseParamList().then((res) => {
        if (res.code == 200) {
          this.basicParams = res.data;
        }
      });
    },
    // 弹窗点确定时获取基本参数、技术参数变更后的数据
    getAfterChangeEquipmentMoveParams() {
      return new Promise((resolve, reject) => {
        if(this.$refs.basicParamsForm && this.$refs.entityForm) {
          Promise.all([this.$refs.basicParamsForm.getFormData(), this.$refs.entityForm.getFormData()]).then(([res1, res2]) => {
            let paramsData = res1
            let entData = res2
            this.$emit('getChangeEquipmentMoveParams', {paramsData, entData, oldEquipmentMoveParams: this.oldEquipmentMoveParams})
            resolve('done')
          })
        } else if (this.$refs.basicParamsForm && !this.$refs.entityForm) {
          Promise.all([this.$refs.basicParamsForm.getFormData()]).then(([res1]) => {
            let paramsData = res1
            this.$emit('getChangeEquipmentMoveParams', {paramsData, oldEquipmentMoveParams: this.oldEquipmentMoveParams})
            resolve('done')
          })
        }
      })
    },
    customColorMethod(percentage) {
      if (percentage < 30) {
        return "#909399";
      } else if (percentage < 70) {
        return "#e6a23c";
      } else {
        return "#67c23a";
      }
    },
    // 是否能编辑内容
    // doEdit() {
    //   this.showEdit = false;
    //   this.basicConfig.itemArr.forEach((item) => {
    //     if (!["code", "amdCode"].includes(item.prop)) {
    //       item.disabled = false;
    //     }
    //   });
    //   this.basicParamsConfig.itemArr.forEach((item) => (item.disabled = false));
    // },
    getFloor() {
      let { id, parentId } = this.treeNode;
      let from = {
        id,
      };
      if (parentId != 0) {
        from.parentId = parentId;
      }
      //新建设备时
      if (this.addType == "root") {
        //根节点新建
        from.id = "";
        from.parentId = "";
      } else if (this.addType == "current") {
        //在当前节点新建
        from.id = "";
        from.parentId = this.treeNode.id;
      }
      getFloorApi(from).then((res) => {
        this.setConfig(res.data);
      });
    },
    setConfig(data) {
      let itemArr = [
        {
          label: "名称",
          prop: "name",
          type: "text",
          required: true,
          span: 24,
        },
        {
          label: "节点类型",
          prop: "isVirtual",
          trigger: "change",
          type: "radio",
          radioOption: this.$store.getters["dirtData"]("equipment_node_type"),
          methods: (obj) => {
            this.treeNode.isVirtual = obj.value;
            this.changeItem();
          },
          span: 12,
          required: true,
        },
        {
          label: "编码",
          prop: "code",
          type: "text",
          placeholder: "自动生成",
          disabled: true,
          required: false,
          span: 12,
        },
        {
          type: "deviceClassify",
          label: "设备分类",
          prop: "typeName",
          idsStr: "typeId",
          placeholder: "请选择设备分类",
          required: true,
          multiple: false,
          maxSelectNum: 1,
          filterMethod: (data) => {
            data.map((i) => {
              if (i.isVirtual == "1") {
                //逻辑分类
                i.disabled = true;
              }
            });
            return data;
          },
          span: 24,
          methods: (arr) => {
            //获取相应分类的参数信息
            if (arr[0]) {
              this.getConfig(arr[0].id);
            } else {
              //删除设备分类时
              this.entityList = [];
              this.basicList = [];
              this.entityConfig.itemArr = [];
              this.basicParamsConfig.itemArr = [];
            }
          },
        },
        {
          type: "select",
          label: "所属层级",
          prop: "floor",
          trigger: "change",
          required: true,
          selectOption: data,
          formatter: (val) => {
            return this.$store.getters["fineDirtDataName"](
              "equipment_level",
              val
            );
          },
          disabledOp: (val, option) => {
            let obj = option.find((i) => i.value == val);
            return obj.disabled;
          },
          span: 12,
        },
        {
          label: "关联组织",
          prop: "deptName",
          idsStr: "deptId",
          type: "dept",
          trigger: "change",
          methods: (obj) => {},
          span: 12,
        },
      ];
      if (this.showEdit) {
        itemArr.map((i) => (i.disabled = true));
      }
      if (this.formData.encode) {
        itemArr[2].prop = "encode";
      } else {
        itemArr[2].prop = "code";
      }
      this.changeItem(itemArr);
      this.showMain = true;
    },
    //判断实体和虚节点，并控制相应项的展示与隐藏
    changeItem(itemArr) {
      let arr = [].concat(this.basicConfig.itemArr);
      if (itemArr) {
        arr = itemArr;
      }
      for (let i in arr) {
        if (["关联组织", "所属层级", "设备分类"].includes(arr[i].label)) {
          if (this.isVirtual) {
            //虚拟节点
            arr[i].isHide = true;
          } else {
            //实体节点
            arr[i].isHide = false;
          }
        }
      }
      this.basicConfig.itemArr = arr;
    },
    //获取节点详情
    getDetails() {
      this.updataType = false;
      getEquipment(this.treeNode.id).then((res) => {
        let data = res.data;
        //获取当前节点对应的所属层级可选值，并设置editForm的Config.itemArr值
        this.getFloor();
        this.formData = data;
        this.basicList = data.basicParams || []; //基本参数
        this.entityList = data.techParams || []; //技术参数

        if(this.parameterList.length && this.popupType === 'edit') {
          let equipId = this.currentNode.id
          const basicMap = new Map()
          const entityMap = new Map()
          
          this.basicList.forEach(item => {
            const key = `${equipId}-${item.paramId}`
            basicMap.set(key, item)
          })
          this.entityList.forEach(item => {
            const key = `${equipId}-${item.paramId}`
            entityMap.set(key, item)
          })

          this.parameterList.forEach(item => {
            const key = `${item.equipId}-${item.paramId}`
            if(basicMap.get(key)) {
              const existItem = basicMap.get(key)
              const { paramNewValue, paramNewResult } = item
              basicMap.set(key, {...existItem, ...{paramValue: paramNewValue, paramResult: paramNewResult}})
            }
            if(entityMap.get(key)) {
              const existItem = entityMap.get(key)
              const { paramNewValue, paramNewResult } = item
              entityMap.set(key, {...existItem, ...{paramValue: paramNewValue, paramResult: paramNewResult}})
            }
          })
          this.basicList = Array.from(basicMap.values())
          this.entityList = Array.from(entityMap.values())
        }

        this.oldEquipmentMoveParams = data.basicParams.reduce((pre, curr) => {
          pre[curr.paramId] = {paramId: curr.paramId, paramName: curr.paramName, paramResult: curr.paramResult, paramValue: curr.paramValue}
          // pre[curr.paramId] = curr.paramValue
          return pre
        }, {})
        this.oldEquipmentMoveParams = data.techParams.reduce((pre, curr) => {
          pre[curr.paramId] = {paramId: curr.paramId, paramName: curr.paramName, paramResult: curr.paramResult, paramValue: curr.paramValue}
          // pre[curr.paramId] = curr.paramValue
          return pre
        }, this.oldEquipmentMoveParams)

        this.updateOldEquipmentMoveParams(this.oldEquipmentMoveParams)
        if (this.basicList.length) {
          this.setEntityConfig(this.basicList, "basicParams");
        } else {
          this.basicParamsConfig.itemArr = [];
          this.basicParamsData = {};
        }
        if (this.entityList.length) {
          this.setEntityConfig(this.entityList, "techParams");
        } else {
          this.entityConfig.itemArr = [];
          this.entityData = {};
        }
        this.customArr = this.getPreviousParams()
      });
    },
    //选择设备编码
    doSelectCode() {
      let data = this.$refs.equipmentCode.getSelectData();
      this.$refs.basicForm.setFormItem("kksCode", data.code);
      this.showCode = false;
    },
    //下载基本参数
    download(command) {
      if (this.menuType == "paramInfor") {
        if (this.currentNode) {
          let path = `eam-service-device/equipment/exportParam?groupId=${command.id}&id=${this.currentNode.id}`;
          let fileName = `${this.currentNode.name}${command.name}基本参数`;
          this.$utils.downloadFile(null, fileName, path);
        }
      } else {
        this.uploadParams = {
          groupId: command.id,
        };
        this.uploadType = "basic";
        this.show = true;
      }
    },
    //导出技术参数
    doExportTechParam() {
      let path = `eam-service-device/paramimp/exportJsParam?eqId=${this.currentNode.id}`;
      let fileName = `${this.currentNode.name}技术参数`;
      this.$utils.downloadFilePost(null, fileName, path);
    },
    //导入技术参数
    doImportTechParam() {
      this.uploadType = "tech";
      this.show = true;
    },
    //文件上传之前
    handleChange(file) {
      let formData = new FormData();
      formData.append("file", file.raw);
      this.uploadFile = formData;
    },
    submitUpload() {
      if (this.uploadType == "basic") {
        uploadBasicParams(this.uploadParams, this.uploadFile).then((res) => {
          if (res.data.msgcode == "ERROR") {
            this.path = `eam-common-web/CommonCon/errorEqExport?filename=${res.data.fileName}`;
            this.fileName = `${res.data.fileName}`;
            this.$message.error("导入失败，请下载错误备注文件查看");
          } else {
            this.$message.success("导入成功");
            this.show = false;
            this.getDetails();
          }
        });
      } else {
        uploadTechParams(this.uploadFile).then((res) => {
          if (res.data.msgcode == "ERROR") {
            let file = res.data.fileName;
            this.path = `eam-common-web/CommonCon/errorEqExport?filename=${file}`;
            this.fileName = `${res.data.fileName}`;
            this.$message.error("导入失败，请下载错误备注文件查看");
          } else {
            this.$message.success("导入成功");
            this.show = false;
            this.getDetails();
          }
        });
      }
    },
    //点击下载批复文件
    downLoadResult() {
      this.$utils.downloadFile(null, this.fileName, this.path);
    },
    //获取图片
    getImage() {
      let businessId = this.treeNode.id;
      if (businessId) {
        let form = {
          businessId,
          businessType: "equipmentManage",
        };
        getAttachList(form).then((res) => {
          let data = res.data || [];
          if (data.length > 0) {
            let { id, path } = data[0];
            this.deviceImg = data[0];
            this.imgIdList = [id];
            this.getImgUrl(id, path);
          } else {
            this.imgUrl = "";
            this.deviceImg = {};
          }
        });
      }
    },
    //通过photo获取图片地址
    async getImgUrl(id, path) {
      let database = localStorage.getItem("currDs") || "";
      if (id) {
        this.imgUrl = await this.$utils.echoImg(id, null, database);
      }
    },
    //设置实体类节点参数表单,以及参数的值
    setEntityConfig(data, type) {
      let entityItem = [];
      let entityFormData = {};
      data.map((i) => {
        //paramResult存value即code;paramValue存lable即name;
        entityFormData[i.paramId] = i.paramValue;
        entityFormData[i.paramId + "Id"] = i.paramResult;
        let inputType = this.changeType(i.enterType);
        inputType = inputType == "radio" ? "select" : inputType;
        if (inputType == "select" && i.enterType == "multi" && i.paramResult) {
          entityFormData[i.paramId + "Id"] = i.paramResult.split(",");
        }
        let item = {
          label: i.paramName,
          prop: i.paramId,
          idsStr: i.paramId + "Id",
          type: inputType,
          required: i.must,
          span: 8,
        };
        if (i.dataUnit && i.dataUnit != "/") {
          item.label = item.label + "(" + i.dataUnit + ")";
        }
        if (inputType == "equipmentBrand" && i.enterType == "trademark") {
          //品牌可输入选择
          item.clearable = true;
          item.propArr = item.idsStr;
          item.option = [];
          item.trigger = "change";
        }
        if (["multi"].includes(i.enterType)) {
          //多选
          item.multiple = true;
        }
        if (["multi_man", "multi_org"].includes(i.enterType)) {
          item.multiple = true;
        }
        if (["radio", "select"].includes(inputType)) {
          item.prop = i.paramId + "Id";
          item.methods = (obj, data) => {
            //paramResult存value即code;paramValue存lable即name;
            if (i.enterType == "multi") {
              let str = [];
              obj.map((k) => {
                if (k) {
                  str.push(k.label);
                }
              });
              data[i.paramId] = str.toString();
            } else {
              data[i.paramId] = obj.label;
            }
          };
          delete item.idsStr;
          let optionName = inputType + "Option";
          if (i.dataText && i.dataText != "") {
            let option = $.parseJSON(i.dataText);
            item[optionName] = option;
          } else {
            //没有选项值，用数据字典的值
            if (i.enterType == "brand") {
              //选厂商
              item[optionName] = this.$store.getters["vendorList"];
            }
          }
        }
        entityItem.push(item);
      });
      if (this.showEdit) {
        entityItem.map((i) => (i.disabled = true));
      }
      if (type == "basicParams") {
        this.basicParamsConfig.itemArr = entityItem;
        this.basicParamsData = entityFormData;
        this.$nextTick(() => {
          this.showCustombasic = true;
        });
      } else if (type == "techParams") {
        this.entityConfig.itemArr = entityItem;
        this.entityData = entityFormData;
        this.$nextTick(() => {
          this.showCustomEntity = true;
        });
      }
      // 判断是否禁用编辑
      if(!this.currentNode.cantSelected) {
        this.basicParamsConfig.itemArr.forEach((item) => {
          item.disabled = false
        });
        this.entityConfig.itemArr.forEach((item) => {
          item.disabled = false
        });
        console.log(this.currentNode.cantSelected)
        console.log(this.basicConfig.itemArr)
      }
    },
    //输入类型
    changeType(type) {
      let inputType = "";
      switch (type) {
        case "radio":
          inputType = "radio";
          break; //单选
        case "multi":
          inputType = "select";
          break; //多选
        case "date_day":
          inputType = "date";
          break; //日期
        case "brand":
          inputType = "select";
          break; //厂商
        case "trademark":
          inputType = "equipmentBrand";
          break; //品牌
        case "date_time":
          inputType = "datetime";
          break; //选日期时间
        case "box":
          inputType = "text";
          break; //文本框
        case "location":
          inputType = "text";
          break; //选位置
        case "radio_org":
          inputType = "dept";
          break; //组织单选
        case "multi_org":
          inputType = "dept";
          break; //选组织-多选
        case "radio_man":
          inputType = "user";
          break; //选人-单选
        case "multi_man":
          inputType = "user";
          break; //选人-多选
      }
      return inputType;
    },
    //获取实体节点的参数列表
    getConfig(id) {
      this.showCustombasic = false;
      this.showCustomEntity = false;
      getConfigApi(id).then((res) => {
        let data = res.data || [];
        this.basicList = data.basic || []; //基本参数
        this.entityList = data.tech || []; //技术参数
        if (this.basicList.length) {
          this.setEntityConfig(data.basic, "basicParams");
        } else {
          this.basicParamsConfig.itemArr = [];
          this.basicParamsData = {};
        }
        if (this.entityList.length) {
          this.setEntityConfig(data.tech, "techParams");
        } else {
          this.entityConfig.itemArr = [];
          this.entityData = {};
        }
      });
    },
    //保存
    async submit() {
      let basicData = await this.$refs.basicForm.getFormData();
      if (this.isVirtual) {
        basicData.typeName = "";
        basicData.typeId = "";
      }
      if (this.pageType == "add") {
        //新增的时候
        if (this.addType == "root") {
          basicData.parentId = "";
          basicData.parentName = "";
        } else {
          let { id, name } = this.treeNode;
          basicData.parentId = id;
          basicData.parentName = name;
        }
      }
      const actionApi = (queryData) => {
        return queryData.id ? updateApi(queryData) : insertApi(queryData);
      };
      if (this.treeNode.isVirtual == 0) {
        //基本参数
        let paramsData = await this.$refs.basicParamsForm.getFormData();
        //把实体参数的值放进paramsList里面
        this.basicList.map((i) => {
          if (Array.isArray(paramsData[i.paramId + "Id"])) {
            i.paramResult = paramsData[i.paramId + "Id"].toString();
          } else {
            i.paramResult = paramsData[i.paramId + "Id"];
          }
          if (Array.isArray(paramsData[i.paramId])) {
            i.paramValue = paramsData[i.paramId].toString();
          } else {
            i.paramValue = paramsData[i.paramId];
          }
        });
        basicData.basicParams = this.basicList;
      } else {
        basicData.basicParams = [];
      }
      if (this.showEntity) {
        //有技术参数
        let entData = await this.$refs.entityForm.getFormData();
        //把实体参数的值放进paramsList里面
        this.entityList.map((i) => {
          if (Array.isArray(entData[i.paramId + "Id"])) {
            i.paramResult = entData[i.paramId + "Id"].toString();
          } else {
            i.paramResult = entData[i.paramId + "Id"];
          }
          if (Array.isArray(entData[i.paramId])) {
            i.paramValue = entData[i.paramId].toString();
          } else {
            i.paramValue = entData[i.paramId];
          }
        });
        basicData.techParams = this.entityList;
      } else {
        //无技术参数
        basicData.techParams = [];
      }
      delete basicData.params;
      actionApi(basicData).then((res) => {
        this.$message.success("操作成功！");
        this.$emit("updateTree", this.pageType);
        this.addType = "";
        // this.getDetails();//会加载两次数据
        this.pageType = "edit";
        this.updataType = true; //用来控制getDetails调用次数
      });
    },
    //删除
    deleteRow() {
      let { id } = this.treeNode;
      this.$confirm(`是否确认删除`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteApi(id).then((res) => {
            this.$message.success("操作成功");
            this.treeNode = {};
            this.formData = {};
            this.showMain = false;
            this.$emit("updateTree");
          });
        })
        .catch((e) => {});
    },
    //移动节点
    moveMethods() {
      this.$refs.moveTree.showDialong = true;
      //this.showSelete = true;
    },
    //查看二维码
    // async viewQrCode(event, type) {
    //   if (type) {
    //     this.fullscreenLoading = true;
    //   }
    //   if (this.treeNode.id) {
    //     this.getCodeImg(type)
    //       .then((res) => {
    //         this.qrCodeUrl = res;
    //         this.fullscreenLoading = false;
    //         this.showQrCode = true;
    //         setTimeout(() => {
    //           this.loadQrCode();
    //         }, 500);
    //       })
    //       .catch((e) => {
    //         this.$message.warning(e);
    //         this.fullscreenLoading = false;
    //         this.showQrCode = true;
    //       });
    //   } else {
    //     this.qrCodeUrl = "";
    //     this.$message.warning("请先选择设备！");
    //   }
    // },
    //下载二维码
    loadQrCode(type = "show") {
      let equipmetName = this.formData.name;
      const canvas = document.getElementById("canvas");
      const ctx = canvas.getContext("2d");
      let imgLog = new Image();
      let imgCode = new Image();
      imgLog.src = this.backgroundImgUrl;
      imgCode.src = this.qrCodeUrl;
      ctx.fillStyle = "rgb(40, 26, 113)";
      ctx.fillRect(0, 340, 280, 80);
      ctx.textAlign = "center";
      ctx.strokeStyle = "white";
      ctx.font = "normal normal 200 14px Microsoft YaHei";
      let strlength1 = ctx.measureText(equipmetName).width;
      ctx.font = "normal normal 200 16px Microsoft YaHei";
      let strlength2 = ctx.measureText(equipmetName).width;
      ctx.font = "normal normal 200 24px Microsoft YaHei";
      let strlength3 = ctx.measureText(equipmetName).width;
      if (strlength1 > 520) {
        ctx.font = "normal normal 200 14px Microsoft YaHei";
        this.canvasTextAutoLine(equipmetName, ctx, 140, 365, 20, canvas);
      } else if (strlength2 > 520 && strlength1 < 520) {
        ctx.font = "normal normal 200 14px Microsoft YaHei";
        this.canvasTextAutoLine(equipmetName, ctx, 140, 375, 20, canvas);
      } else if (strlength2 > 260) {
        ctx.font = "normal normal 200 16px Microsoft YaHei";
        this.canvasTextAutoLine(equipmetName, ctx, 140, 375, 20, canvas);
      } else if (strlength3 > 260 && strlength2 < 260) {
        ctx.font = "normal normal 200 16px Microsoft YaHei";
        this.canvasTextAutoLine(equipmetName, ctx, 140, 385, 20, canvas);
      } else {
        ctx.font = "normal normal 200 24px Microsoft YaHei";
        this.canvasTextAutoLine(equipmetName, ctx, 140, 385, 20, canvas);
      }
      let imageData = ctx.getImageData(0, 0, 280, 420);
      for (let i = 0; i < imageData.data.length; i += 4) {
        // 当该像素是透明的,则设置成白色
        if (imageData.data[i + 3] == 0) {
          imageData.data[i] = 255;
          imageData.data[i + 1] = 255;
          imageData.data[i + 2] = 255;
          imageData.data[i + 3] = 255;
        }
      }
      ctx.putImageData(imageData, 0, 0);
      let url = canvas.toDataURL("image/jpg");
      this.canvasUrl = url;
      imgLog.onload = () => {
        ctx.drawImage(imgLog, 30, 20, 220, 34);
        let url = canvas.toDataURL("image/jpg");
        this.canvasUrl = url;
      };
      imgCode.onload = () => {
        ctx.drawImage(imgCode, 20, 80, 240, 240);
        let url = canvas.toDataURL("image/jpg");
        this.canvasUrl = url;
      };
    },
    downloadQrCode(type = "show") {
      let equipmetName = this.formData.name;
      const canvas = document.createElement("canvas");
      canvas.width = "560";
      canvas.height = "840";
      const ctx = canvas.getContext("2d");
      ctx.fillStyle = "rgb(40, 26, 113)";
      ctx.fillRect(0, 680, 560, 160);
      ctx.textAlign = "center";
      ctx.strokeStyle = "white";
      ctx.font = "normal normal 200 28px Microsoft YaHei";
      let strlength1 = ctx.measureText(equipmetName).width;
      ctx.font = "normal normal 200 32px Microsoft YaHei";
      let strlength2 = ctx.measureText(equipmetName).width;
      ctx.font = "normal normal 200 40px Microsoft YaHei";
      let strlength3 = ctx.measureText(equipmetName).width;
      if (strlength1 > 1080) {
        ctx.font = "normal normal 200 28px Microsoft YaHei";
        this.canvasTextAutoLine(equipmetName, ctx, 280, 730, 40, canvas);
      } else if (strlength2 > 1080 && strlength1 < 1080) {
        ctx.font = "normal normal 200 28px Microsoft YaHei";
        this.canvasTextAutoLine(equipmetName, ctx, 280, 750, 40, canvas);
      } else if (strlength2 > 520) {
        ctx.font = "normal normal 200 32px Microsoft YaHei";
        this.canvasTextAutoLine(equipmetName, ctx, 280, 750, 40, canvas);
      } else if (strlength3 > 520 && strlength2 < 520) {
        ctx.font = "normal normal 200 32px Microsoft YaHei";
        this.canvasTextAutoLine(equipmetName, ctx, 280, 770, 40, canvas);
      } else {
        ctx.font = "normal normal 200 40px Microsoft YaHei";
        this.canvasTextAutoLine(equipmetName, ctx, 280, 770, 40, canvas);
      }
      let imageData = ctx.getImageData(0, 0, 560, 840);
      for (let i = 0; i < imageData.data.length; i += 4) {
        // 当该像素是透明的,则设置成白色
        if (imageData.data[i + 3] == 0) {
          imageData.data[i] = 255;
          imageData.data[i + 1] = 255;
          imageData.data[i + 2] = 255;
          imageData.data[i + 3] = 255;
        }
      }
      ctx.putImageData(imageData, 0, 0);
      let p1 = new Promise((resolve, reject) => {
        let imgLog = new Image();
        imgLog.src = this.backgroundImgUrl;
        imgLog.onload = () => {
          ctx.drawImage(imgLog, 40, 20, 400, 100);
          resolve(true);
        };
      });
      let p2 = new Promise((resolve, reject) => {
        let imgCode = new Image();
        imgCode.src = this.qrCodeUrl;
        imgCode.onload = () => {
          ctx.drawImage(imgCode, 40, 160, 480, 480);
          resolve(true);
        };
      });
      Promise.all([p1, p2])
        .then((res) => {
          let url = canvas.toDataURL("image/jpg");
          this.canvasUrl = url;
          let a = document.createElement("a");
          let event = new MouseEvent("click");
          a.download = equipmetName + "-二维码.png";
          a.href = url;
          a.dispatchEvent(event);
        })
        .catch((e) => {
          console.log(e);
        });
    },
    //查看二维码
    async viewQrCode(event, type) {
      console.log(this.currentNode);
      this.showQrCode = true;
      this.$nextTick(() => {
        let params = { org: "yhsw" };
        this.currentNode.encode && (params.kks = this.currentNode.encode);
        this.currentNode.code && (params.code = this.currentNode.code);
        let json = JSON.stringify(params);
        new QRCode(this.$refs.qrCodeUrl, {
          text: json, // 需要转换为二维码的内容
          width: 250,
          height: 250,
          colorDark: "#000000",
          colorLight: "#ffffff",
          correctLevel: QRCode.CorrectLevel.L,
        });
      });
      setTimeout(() => {
        let el = document.querySelectorAll(".QRCode img");
        this.qrCodeUrl = el[0].src;
        this.loadQrCode();
      }, 100);
    },
    // //下载二维码
    // loadQrCode() {
    //   let el = document.querySelectorAll(".QRCode img");
    //   let url = el[0].src;
    //   let base64 = url.toString(); // imgSrc 就是base64哈
    //   let byteCharacters = atob(
    //     base64.replace(/^data:image\/(png|jpeg|jpg);base64,/, "")
    //   );
    //   let byteNumbers = new Array(byteCharacters.length);
    //   for (let i = 0; i < byteCharacters.length; i++) {
    //     byteNumbers[i] = byteCharacters.charCodeAt(i);
    //   }
    //   let byteArray = new Uint8Array(byteNumbers);
    //   let blob = new Blob([byteArray], {
    //     type: undefined,
    //   });
    //   let a = document.createElement("a");
    //   document.body.appendChild(a);
    //   a.download = `${this.currentNode.name}-二维码.png`; //这里写保存时的图片名称
    //   a.href = URL.createObjectURL(blob);
    //   a.click();
    //   window.URL.revokeObjectURL(url); //下载完成进行释放
    //   document.body.removeChild(a);
    // },
    //批量下载二维码
    async downloadQRcode() {
      try {
        let res = await getEquipmentByParentId({
          parentId: this.currentNode.id,
        });
        let list = [];
        res.data.forEach((item) => {
          list.push({
            name: item.name,
            org: "yhsw",
            kks: item.encode,
            code: item.code,
          });
        });
        let time = 50 * list.length;
        this.$refs.qrCode.createQrCode(list, this.currentNode.name, time);
        this.visible = true;
        this.percentage = 0;
        this.timerInterval = setInterval(() => {
          let step = parseInt(2000 / list.length);
          this.percentage += step;
          if (this.percentage > 100) {
            this.percentage = 99;
            // this.visible = false;
            // clearInterval(this.timerInterval);
          }
        }, 1000);
      } catch (error) {
        console.log(error);
      }
    },
    downLoadSuccess() {
      this.percentage = 100;
      this.visible = false;
      clearInterval(this.timerInterval);
    },
    /*
     str:要绘制的字符串
     ctx:canvas对象
     initX:绘制字符串起始x坐标
     initY:绘制字符串起始y坐标
     lineHeight:字行高，自己定义个值即可
*/
    canvasTextAutoLine(str, ctx, initX, initY, lineHeight, c) {
      let lineWidth = 0;
      let canvasWidth = c.width - 20;
      let lastSubStrIndex = 0;
      for (let i = 0; i < str.length; i++) {
        lineWidth += ctx.measureText(str[i]).width;
        if (lineWidth > canvasWidth) {
          //减去initX,防止边界出现的问题
          ctx.strokeText(
            str.substring(lastSubStrIndex, i),
            initX,
            initY,
            canvasWidth
          );
          initY += lineHeight;
          lineWidth = 0;
          lastSubStrIndex = i;
        }
        if (i == str.length - 1) {
          ctx.strokeText(
            str.substring(lastSubStrIndex, i + 1),
            initX,
            initY,
            canvasWidth
          );
        }
      }
    },
    /**导出 */
    async exportDevices(type, errorName = "") {
      this.fullscreenLoading = true;
      let blob = null;
      let name = "";
      if (type == "equipment") {
        let form = {
          equipmentId: this.currentNode.id,
          fileName: this.currentNode.name,
        };
        name = this.currentNode.name;
        blob = await exportDevicesApi(form);
      } else if (type == "model") {
        name = "台账模板";
        blob = await exportModelApi();
      } else if (type == "error") {
        name = this.currentNode.name + "导入错误文件";
        let form = {
          filename: errorName,
        };
        blob = await exportErrorApi(form);
      }
      let reader = new FileReader();
      let that = this;
      reader.readAsDataURL(blob);
      reader.onload = function (e) {
        let a = document.createElement("a");
        document.body.appendChild(a);
        a.href = e.target.result;
        a.download = name + ".xls";
        a.click(); //点击触发下载
        document.body.removeChild(a);
        that.fullscreenLoading = false;
      };
    },

    getCodeImg(preview = true) {
      let that = this;
      //默认为true,预览
      return new Promise((resolve, reject) => {
        let url = "";
        let pageUrl = "pages/equiLedger/equiDetail";
        let { id, name } = this.treeNode;
        name = name.replace(/\#/g, "%23"); //特殊字符转换
        let nodeEnv = process.env.NODE_ENV;
        let envVersion = null;
        if (process.env.NODE_ENV == "development") {
          //开发环境
          envVersion = "develop";
        } else if (process.env.NODE_ENV == "production") {
          //生产环境
          envVersion = "release";
        }
        if (id) {
          url = `${process.env.VUE_APP_BASEURL}/eam-common-web/qrCode/miniProgram/create?page=${pageUrl}&scene=${id}&preview=${preview}&eqName=${name}&envVersion=${envVersion}`;
        }
        let token = "",
          source = "";
        if (localStorage.getItem("GDH_WATER_TOKEN")) {
          token = localStorage.getItem("GDH_WATER_TOKEN");
          source = localStorage.getItem("currDs");
        } else {
          token = process.env.VUE_APP_TOKEN;
        }
        let xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.setRequestHeader(
          "Content-type",
          "application/x-www-form-urlencoded"
        );
        xhr.setRequestHeader("jwt_token", token);
        xhr.setRequestHeader("DYNAMIC_DATA_SOURCE", source);
        xhr.send();
        xhr.responseType = "blob";
        xhr.onload = function () {
          if (this.status == 200) {
            let blob = this.response;
            this.codeData = blob;
            if (preview) {
              that.$utils.blobToBase64(blob, (res) => {
                resolve(res);
              });
            } else {
              let reader = new FileReader();
              reader.readAsDataURL(blob);
              reader.onload = function (e) {
                let a = document.createElement("a");
                document.body.appendChild(a);
                a.href = e.target.result;
                a.download = that.treeNode.name + "-二维码.jpg";
                a.click(); //点击触发下载
                window.URL.revokeObjectURL(url); //下载完成进行释放
                document.body.removeChild(a);
              };
            }
          } else {
            reject("二维码请求出错！");
          }
        };
      });
    },

    //新建
    toAdd(type) {
      this.entityConfig.itemArr = [];
      this.entityData = {};
      this.basicParamsConfig.itemArr = [];
      this.basicParamsData = {};

      this.addType = type;
      this.$refs.addBtn.$el.click();
      this.pageType = "add";
      this.getFloor();
      this.treeNode.isVirtual = "1";
      this.formData = { isVirtual: "1" };
    },
    //取消新建
    cancel() {
      this.pageType = "edit";
      this.addType = "";
      this.treeNode = Object.assign({}, this.currentNode);
      this.getDetails();
      this.getImage();
    },
    //提交移动节点
    submitNode(form) {
      moveNode(form).then((res) => {
        this.$message.success("操作成功");
        this.treeNode = {};
        this.formData = {};
        this.showMain = false;
        // 移动节点要保留
        this.$emit("updateTree", true);
      });
    },
    //设置实体参数的值
    setEntityData(data) {
      this.paramsList.map((i) => {
        i.paramValue = data[i.paramId];
        i.paramResult = data[i.paramId + "Id"];
      });
    },
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 <= 1;
      if (!isJPG || !isLt2M) {
        if (!isJPG) {
          this.$message.error("上传头像图片只能是 JPG 格式!");
        } else if (!isLt2M) {
          this.$message.error("上传头像图片大小不能超过 2MB!");
        }
      }
      return isJPG && isLt2M;
    },
    //选择完文件之后
    changeFile(file, fileList) {
      if (!this.isInstantUpload) {
        if (this.beforeUpload(file.raw, fileList)) {
          this.newUploadObj.files.push(file.raw);
        } else {
          fileList.map((i, index) => {
            if (i.uid == file.uid) {
              this.$refs.upload.uploadFiles.splice(index, 1);
            }
          });
        }
      }
    },

    /* 设备图片*/
    handleRemove() {
      let { id } = this.deviceImg;
      this.$confirm(
        "此操作将删除【" + this.currentNode.name + "】的照片, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          deleteFiles(id)
            .then((res) => {
              this.imgUrl = "";
              this.deviceImg = {};
              this.$message.success("文件删除成功！");
            })
            .catch((e) => {
              this.$message.warning("文件删除失败！");
            });
        })
        .catch((e) => {});
    },
    handlePictureCardPreview() {
      prevOverflow = document.body.style.overflow;
      document.body.style.overflow = "hidden";
      this.showViewer = true;
    },
    handleDownload() {
      let { id, extension } = this.deviceImg;
      let name = this.currentNode.name + "." + extension;
      this.$utils.downloadFile(id, name);
    },

    //立即保存图片
    saveItemFile(file) {
      let formData = new FormData();
      let businessId = this.treeNode.id;
      if (businessId) {
        formData.append("files", file.file);
        let form = {
          businessId,
          businessType: "equipmentManage",
        };
        uploadFileApi(form, formData)
          .then((res) => {
            this.$refs.fileUpload.clearFiles();
            this.getImage();
            this.$message.success("保存成功！");
          })
          .catch((res) => {
            this.$message.warning("文件上传失败,请重新上传！");
          });
      }
    },
    //台账导入
    saveFiles(file) {
      let formData = new FormData();
      formData.append("file", file.file);
      let form = {
        id: this.currentNode.id,
      };
      uploadParameterApi(form, formData).then((res) => {
        let data = res.data;
        if (data.msgcode == "ERROR") {
          this.errorFileName = data.fileName;
          this.$confirm("导入错误，是否下载错误文件？")
            .then((_) => {
              this.exportDevices("error", data.fileName);
            })
            .catch((e) => {});
        } else if (data.msgcode == "SUCCESS") {
          this.$message.success("操作成功！");
          this.getDetails();
          this.getImage();
        }
      });
    },
    //打印
    printCode() {
      this.$print(this.$refs.codeImg);
    },
    closeViewer() {
      document.body.style.overflow = prevOverflow;
      this.showViewer = false;
    },
  },
};
</script>
<style lang="less" scoped>
.basicInfo {
  .editBtn {
    display: inline-block;
    margin-right: 10px;
  }
  .imgBlock {
    width: 300px;
    height: 150px;
  }
  .constentTop {
    justify-content: flex-end;
    margin-bottom: 15px;
    padding-right: 15px;
  }
  .queryInput {
    /deep/.el-input__inner {
      height: 30px;
      line-height: 30px;
    }
  }
  .constentmain {
    margin-left: 15px;
  }
  .popoverBtn + .el-button--primary {
    margin-left: 10px;
  }
  .el-button--primary {
    background-color: #2c77f4 !important;
    border-color: #2c77f4 !important;
  }
  .constentBttom {
    height: calc(100% - 28px);
    overflow: auto;
  }
}
.addBtn:hover {
  color: @kr-elementUI-color;
  cursor: pointer;
}
.flowCloumn {
  display: flex;
  flex-flow: column nowrap;
}
.flowWrap {
  display: flex;
  flex-flow: wrap nowrap;
}
.addBtn {
  .el-button:focus,
  .el-button:hover {
    background-color: #ffffff;
    color: @kr-elementUI-color;
  }
}
.importBtn {
  border: none;
  padding: 0px;
}
.baseDiv {
  display: flex;
  flex-flow: wrap nowrap;
  .formDiv {
    width: 100%;
  }
  .imgDiv {
    margin: 0px 35px;
    display: flex;
    flex-flow: wrap nowrap;
    width: 43.3%;
    // width: 300px;
    height: 144px;
    .imgLeft {
      width: 144px;
      height: 144px;
      border-radius: 4px;
      background: #f8f8f8;
      overflow: hidden;
      position: relative;
      .elImg {
        width: 144px !important;
        height: 144px !important;
        display: table;
      }
      /deep/.errText {
        height: 100% !important;
        display: table-cell;
        vertical-align: middle;
      }
      .el-icon-picture-outline {
        font-size: 130px;
        color: #e0e0e0;
      }
      .el-icon-camera {
        font-size: 80px;
        color: #e0e0e0;
      }
    }
    .imgRight {
      margin-left: 15px;
      width: 144px;
      height: 144px;
      text-align: left;
      display: table;
      .imgText {
        display: table-cell;
        vertical-align: middle;
        width: 100%;
        height: 100%;
      }
    }
    .el-upload-actions {
      width: 100%;
      height: 100%;
      position: absolute;
      opacity: 0;
      left: 0;
      top: 0;
      color: #fff;
      text-align: center;
      font-size: 24px;
      background-color: rgba(0, 0, 0, 0.5);
      cursor: default;
      transition: opacity 0.3s;
      line-height: 144px;
    }
    .el-upload-icon {
      display: inline-block;
      width: 50%;
      height: 100%;
    }
    .el-upload-icon + .el-upload-icon {
      margin-left: 0px;
    }
    .el-upload-actions:hover {
      opacity: 1;
    }
    .el-upload-icon:hover {
      cursor: pointer;
    }
  }
}
.btnSpan {
  margin-left: 10px;
}
.codeContent {
  width: 100%;
  text-align: center;
  display: flex;
  flex-flow: column nowrap;
  justify-content: center;
  align-items: center;
}
.codeDiv {
  position: absolute;
  width: 300px;
  height: 510px;
  background-color: #ffffff;
  border: 1px solid #e4e4e4;
  border-radius: 4px;
  top: 120px;
  right: 10px;
  z-index: 999;
  .codeTop {
    display: flex;
    flex-flow: wrap nowrap;
    justify-content: space-between;
    .codeClose {
      padding: 5px 15px;
      cursor: pointer;
    }
  }
  .codeTitle {
    text-align: left;
    padding: 5px 15px;
  }
  .codeBtn {
    padding: 15px;
  }
}
.topDistance {
  top: 40px;
}
.dayInput {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .location {
    font-size: 20px;
    color: #00468e;
    cursor: pointer;
  }
}
.address {
  margin: 2px 0;
  cursor: pointer;
}
#canvas {
  border: 1px solid rgb(116, 116, 116);
  border-radius: 10px;
  letter-spacing: 2px;
  background-color: #fff;
}
.moreBtnContent {
  display: flex;
  flex-flow: column nowrap;
  .tipContent {
    height: auto;
    .moreItem {
      height: 30px;
      line-height: 30px;
    }
  }
}
.moreBtnContent {
  .el-popover__reference-wrapper {
    .el-button {
      border: none;
      padding: 0px;
    }
    .el-button:focus,
    .el-button:hover {
      background-color: transparent;
      color: @kr-elementUI-color;
    }
  }
  .moreItem + .moreItem {
    margin-top: 10px;
  }
  .moreItemText {
    cursor: pointer;
  }
}
</style>